package com.dyava.commons.clock;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.concurrent.TimeUnit;

/**
 * Created by jjliu on 2020/4/16.
 */
public abstract class ClockSender {

    public <T>void clock(Class<?> clockHandleClass,T args, int num, TimeUnit timeUnit){
       clock(StringUtils.uncapitalize(clockHandleClass.getSimpleName()),args,num,timeUnit);
    }
    public <T>void clock(String clockHandleName,T args, int num, TimeUnit timeUnit){
        ClockMessage clockMessage = new ClockMessage();
        clockMessage.setHandleName(clockHandleName);
        clockMessage.setArgs(JSON.toJSONString(args));
        long timestamp = System.currentTimeMillis()+timeUnit.toMillis(num);
        send(clockMessage,timestamp);
    }

    public <T>void clockAt(Class<?> clockHandleClass,T args, LocalDateTime time){
        clockAt(StringUtils.uncapitalize(clockHandleClass.getSimpleName()),args,time);
    }

    public <T>void clockAt(String clockHandleName,T args, LocalDateTime time){
        ClockMessage clockMessage = new ClockMessage();
        clockMessage.setHandleName(clockHandleName);
        clockMessage.setArgs(JSON.toJSONString(args));
        long timestamp = time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        send(clockMessage,timestamp);
    }

    protected abstract void send(ClockMessage clockMessage,long timestamp);

}
